<?php

namespace app\admin\controller;

use app\admin\model\Lang;
use app\admin\model\LangClass;
use app\common\controller\Send;
use app\common\enums\StatusEnum;
use think\facade\Request;
use app\admin\model\OauthOrder AS OrderModel;
use app\admin\validate\OauthOrder AS OrderValidate;
use app\admin\model\CustomerService;

class OauthOrder extends Base
{
    use Send;

    public function common()
    {
        $search = input('');
        $couponId = isset($search['coupon_id']) ? $search['coupon_id'] : -1;
        $oauthId = isset($search['oauth_id']) ? $search['oauth_id'] : 0;
        $type = isset($search['type']) ? $search['type'] : -1;
        $shareUid = isset($search['share_uid']) ? $search['share_uid'] : 0;
        $orderSn = isset($search['order_sn']) ? $search['order_sn'] : '';
        $oauthNickname = isset($search['oauth_nickname']) ? $search['oauth_nickname'] : '';
        $langId = isset($search['lang_id']) ? $search['lang_id'] : -1;
        $customerId = isset($search['customer_id']) ? $search['customer_id'] : -1;
        $couponName = isset($search['coupon_name']) ? $search['coupon_name'] : '';
        $payType = isset($search['pay_type']) ? $search['pay_type'] : '';
        $payMoney = isset($search['pay_money']) ? $search['pay_money'] : '';
        $startTime = isset($search['start_time']) ? $search['start_time'] : '';
        $endTime = isset($search['end_time']) ? $search['end_time'] : '';
        $search = [
            'share_uid' => $shareUid,
            'coupon_id' => $couponId,
            'oauth_id' => $oauthId,
            'type' => $type,
            'order_sn' => $orderSn,
            'oauth_nickname' => $oauthNickname,
            'lang_id' => $langId,
            'customer_id' => $customerId,
            'coupon_name' => $couponName,
            'pay_type' => $payType,
            'pay_money' => $payMoney,
            'start_time' => $startTime,
            'end_time' => $endTime
        ];
        $where = [];
        if ($search['coupon_id'] != null && $search['coupon_id'] != -1) {
            $where[] = ['coupon_id', '=', $search['coupon_id']];
        }

        if ($search['oauth_id'] > 0) {
            $where[] = ['oauth_id', '=', $search['oauth_id']];
        }

        if ($search['share_uid'] > 0) {
            $where[] = ['share_uid', '=', $search['share_uid']];
        }
        if ($search['pay_money'] != null && $search['pay_money'] != -1) {
            if ($search['pay_money'] == 1) {
                $where[] = ['pay_money', '>', 0];
            }
            if ($search['pay_money'] == 2) {
                $where[] = ['pay_money', '=', 0];
            }
        }
        if ($search['type'] != null && $search['type'] != -1) {
            $where[] = ['type', '=', $search['type']];
        }

        if ($search['order_sn']) {
            $where[] = ['order_sn', 'like', '%' . $search['order_sn'] . '%'];
        }

        if ($search['oauth_nickname']) {
            $where[] = ['oauth_nickname', 'like', '%' . $search['oauth_nickname'] . '%'];
        }

        if ($search['lang_id'] != null && $search['lang_id'] != -1) {
            $where[] = ['lang_id', '=', $search['lang_id']];
        }

        if ($search['customer_id'] != null && $search['customer_id'] != -1) {
            $where[] = ['customer_id', '=', $search['customer_id']];
        }

        if ($search['coupon_name']) {
            $where[] = ['coupon_name', 'like', '%' . $search['coupon_name'] . '%'];
        }

        if ($search['pay_type'] != null && $search['pay_type'] != -1) {
            $where[] = ['pay_type', '=', $search['pay_type']];
        }

        if ($search['start_time']) {
            $where[] = ['create_time', '>=', strtotime($search['start_time'])];
        }

        if ($search['end_time']) {
            $where[] = ['create_time', '<=', strtotime($search['end_time'])];
        }

        $model = OrderModel::getList($where);

        return [
            'title' => '订单列表',
            'noNickname' => 0,
            'noCoupon' => 0,
            'detailType' => 1,
            'parentUrl' => '',
            'parentName' => '',
            'model' => $model['model'],
            'count' => $model['count'],
            'money' => $model['money'],
            'commission' => $model['commission'],
            'search' => $search,
            'type' => OrderModel::attributes('type'),
            'oauthId' => $search['oauth_id'],
            'lang' => Lang::getColumn(),
            'payMoney' => $search['pay_money'],
            'customer' => CustomerService::getColumn(),
            'payType' => OrderModel::attributes('pay_type')

        ];
    }

    /**
     * 列表
     * @return \think\response\View
     */
    public function index()
    {
        $data = $this->common();
        $data['cancelUrl'] = url('index');
        return view('index', $data);
    }

    /**
     * 我的课程
     * @return \think\response\View
     */
    public function mine()
    {
        $data = $this->common();
        $data['title'] = '我的课程';
        $data['noNickname'] = 1;
        $data['parentUrl'] = url('oauth/index');
        $data['parentName'] = '用户管理';
        $data['detailType'] = 2;
        $data['cancelUrl'] = url('mine', ['oauth_id' => $data['search']['oauth_id']]);
        return view('index', $data);
    }

    /**
     * 我的分享
     * @return \think\response\View
     */
    public function share()
    {
        $data = $this->common();
        $data['title'] = '我的分享';
        $data['noNickname'] = 1;
        $data['parentUrl'] = url('oauth/index');
        $data['parentName'] = '用户管理';
        $data['detailType'] = 3;
        $data['cancelUrl'] = url('share', ['share_uid' => $data['search']['share_uid']]);
        return view('index', $data);
    }

    /**
     * 优惠券相关订单
     * @return \think\response\View
     */
    public function coupon()
    {
        $data = $this->common();
        $data['title'] = '相关订单';
        $data['parentUrl'] = url('coupon/index');
        $data['parentName'] = '优惠券管理';
        $data['detailType'] = 4;
        $data['noCoupon'] = 1;
        $data['cancelUrl'] = url('coupon', ['coupon_id' => $data['search']['coupon_id']]);
        return view('index', $data);
    }

    /**
     * 添加修改
     * @return \think\response\Json|\think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function form()
    {
        if (Request::instance()->isPost()) {
            $data = input('post.');

            // 检测变量
            $validate = new OrderValidate();
            if (!$validate->check($data)) {
                return json(self::sendResult(102, [], $validate->getError()));
            }
            if (empty($data['pay_money_to'])) {
                return json(self::sendResult(102, [], '请选择是否付费'));
            }
            if (!empty($data['pay_money_to']) && $data['pay_money'] <= '0.00') {
                return json(self::sendResult(102, [], '请输入正确的金额'));
            }
            // 添加订单和订单相关系列数据
            $res = OrderModel::saveOne($data);

            return json(self::sendResult($res['code'], [
                'url' => url('mine', ['oauth_id' => $data['oauth_id']]),
            ], $res['msg']));
        } else {
            $oauthId = input('oauth_id') ? input('oauth_id') : 0;
            $info = OrderModel::buyInfo($oauthId);
            return view('form', [
                'status' => StatusEnum::$listExplain,
                'lang' => Lang::getColumn(),
                'class' => LangClass::attributes('type'),
                'customer' => $info['customers'],
                'reduceMoney' => $info['reduceMoney'],
                'coupon' => $info['coupon'],
                'oauth' => $info['oauth'],
                'payType' => OrderModel::attributes('pay_type')
            ]);
        }
    }

    /**
     * 订单备注
     * @return \think\response\Json
     */
    public function remark()
    {
        if (Request::instance()->isPost()) {
            $data = input('post.');
            if (empty($data['id'])) {
                return json(self::sendResult(602, [], '缺少必要参数'));
            }

            // 订单备注
            OrderModel::remark($data);

            return json(self::sendResult(self::$okCode, [
                'url' => url('index')
            ]));
        }
        return json(self::sendResult(602, [], '非法调用'));
    }

    /**
     * 订单详情
     * @param $id
     * @return \think\response\View
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function detail($id)
    {
        $model = OrderModel::getOne($id);
        $detailType = input('detailType');
        switch ($detailType) {
            case 2:
                $title = '我的课程';
                $url = url('mine', ['oauth_id' => $model['oauth_id']]);
                break;
            case 3:
                $title = '我的分享';
                $url = url('share', ['share_uid' => $model['share_uid']]);
                break;
            case 4:
                $title = '相关订单';
                $url = url('coupon', ['coupon_id' => $model['coupon_id']]);
                break;
            default:
                $title = '订单';
                $url = url('index');
                break;
        }
        return view('detail', [
            'model' => $model,
            'title' => $title,
            'url' => $url
        ]);
    }
    
    
    /**
     * 删除订单
     * @param $id
     * @return array
     */
    public function delete($id)
    {
        OrderModel::deleteOne($id);
        return self::sendResult(self::$okCode, [
            'url' => url('index'),
        ]);
    }
}
